/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.security.filter.applet;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.Serializable;
import java.util.Map;
import lombok.Getter;
import lombok.experimental.SuperBuilder;
import org.elsfs.cloud.common.security.filter.applet.wechat.WechatAppletAuthorizationRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 小程序请求参数
 *
 * @author zeng
 */
@SuperBuilder
@Getter
public abstract class AppletAuthorizationRequest implements Serializable {
  protected static final RestTemplate REST_OPERATIONS = new RestTemplate();
  protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

  protected String appid;
  protected String state;
  protected AppletType type;
  protected String phoneCode;
  protected Map<String, String> additionalParameters;
  protected String openidCode;
  protected String openidUrl;

  /**
   * 转换为 map
   *
   * @return map
   */
  public abstract MultiValueMap<String, String> toMap();

  public abstract ResponseBody requestOpenid();

  public abstract String requestPhone();

  /**
   * 获取AppletAuthorizationRequest
   *
   * @param clientRegistration clientRegistration
   * @param params params
   * @param appletType appletType
   * @return AppletAuthorizationRequest
   */
  public static AppletAuthorizationRequest getAppletAuthorizationRequest(
      ClientRegistration clientRegistration,
      MultiValueMap<String, String> params,
      AppletType appletType) {
    if (appletType.equals(AppletType.WECHAT_MINI)) {
      return WechatAppletAuthorizationRequest.builder()
          .type(appletType)
          .appid(params.getFirst(AppletParameterNames.APPID))
          .openidCode(params.getFirst(AppletParameterNames.AUTH_CODE))
          .secret(clientRegistration.getClientSecret())
          .phoneCode(params.getFirst(AppletParameterNames.PHONE_CODE))
          .build();
    }
    return null;
  }
}
